package org.example.commerce.imp.controller;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.commerce.api.beans.ModifyUserParam;
import org.example.commerce.api.beans.NewUserParam;
import org.example.commerce.dao.entity.User;
import org.example.common.response.R;

import org.example.commerce.imp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService  userService;

    /**
     * 用户登录
     */
    @GetMapping("/login/{username}/{password}")
    public R<User> login(HttpServletRequest request, @PathVariable String username , @PathVariable String password){
        return userService.userLogin(request,username,password);
    }

    /**
     * 用户退出
     */
    @PostMapping("/logout/")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录的员工id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    /**
     * 查询所有用户
     */
    @GetMapping("/{page}/{pageSize}")
    public R<PageInfo<User>> userPage(@PathVariable Integer page, @PathVariable Integer pageSize){
        log.info("get all Users page={} pageSize={}",page,pageSize);
        return userService.users(page,pageSize);
    }

    /**
     * 通过ID查询用户
     */
    @GetMapping("/{id}")
    public User userSelectById(@PathVariable Integer id){
        log.info("select user by id {}",id);
        return userService.selectById(id);
    }

    /**
     * 新增员工
     */
    @PostMapping("/")
    public R<User> userSave(HttpServletRequest request, @RequestBody NewUserParam user){
        log.info("save new user data{}",user);
        return userService.userSave(request,user);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public R<String> deleteUserById(@PathVariable Long id){
        log.info("delete user by id = {}", id);
        return userService.deleteUserById(id);
    }

    /**
     * 修改用户
     */
    @PutMapping("/")
    public R<User> modifyUser(@RequestBody ModifyUserParam user){
        return userService.modifyUser(user);
    }

    /**
     *修改用户状态
     */
    @PutMapping("/{id}")
    public R<User> setUserStatus(@PathVariable Integer id){
        log.info("set user status id = {}",id);
        return userService.setUserStatus(id);
    }
}
